﻿using System;
using System.Collections.Generic;
using System.Data.SqlTypes;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AppStore.Domain.Abstract;
using AppStore.Domain.Entities;
using PagedList;

namespace AppStore.Controllers
{
    public class ApplicationController : Controller
    {
        private IApplicationRepository _applicationRepository;
        private ICommentsRepository _commentsRepository;
        private const int pageSize = 3;

        public ApplicationController(IApplicationRepository applicationRepository,ICommentsRepository commentsRepository)
        {
            _applicationRepository = applicationRepository;
            _commentsRepository = commentsRepository;     
        }

        public ActionResult Browse(string category, int? page)
        {
            var appsChoosedByCategory = _applicationRepository.Applications.Where(a => a.Category.name == category).OrderBy(a => a.name);
            page = page ?? 1;
            return View(appsChoosedByCategory.ToPagedList((int)page,pageSize));
        }

        public ActionResult Details(int applicationId)
        {
            var application = _applicationRepository.Applications.SingleOrDefault(a => a.applicationId == applicationId);
            var comment = _commentsRepository.Comments.Where(c => c.applicationId == applicationId).ToList();
            ViewBag.Comments = comment;
            ViewBag.Average = (double)comment.Sum(c => c.rating)/comment.Count;

            return View(application);
        }

        [HttpPost]
        public ActionResult AddComment(string commentText,string rate, string returnUrl,int applicationId)
        {
            var comment = new Comment();
            comment.comment = commentText;
            comment.applicationId = applicationId;
            comment.rating = int.Parse(rate);

            _commentsRepository.addComment(comment);
           
            return Redirect(returnUrl);
        }

        public FileContentResult GetImage(int applicationId)
        {
            Application app = _applicationRepository.Applications.SingleOrDefault(a => a.applicationId == applicationId);
            if (app.ImageData != null)
                return File(app.ImageData, app.ImageMimeType);
            else
                
                //return File(System.IO.File.ReadAllBytes(Url.Content("C:\\Users\\Krzysztof\\documents\\visual studio 2012\\Projects\\AppStore\\AppStore\\Content\\Images\\01.jpg")), "image/jpeg");
                return File(System.IO.File.ReadAllBytes(Server.MapPath("~/Content/Images/01.jpg")), "image/jpeg");
        }
    }
}